<template>
  <div class="main">
    <div class="article-manager">
      <!-- 页面标题 -->
      <h2 class="page-title">我的文章管理</h2>

      <!-- 搜索和Tabs -->
      <div class="control-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文章标题..."
          clearable
          class="custom-search"
        >
          <template #prefix>
            <el-icon class="search-icon"><Search /></el-icon>
          </template>
        </el-input>

        <el-tabs v-model="activeTab" class="status-tabs">
          <el-tab-pane :label="`全部(${posts.length})`" :name="STATUS.ALL"/>
          <el-tab-pane :label="`已发布(${statusCount[STATUS.PUBLISHED]})`"
                       :name="STATUS.PUBLISHED"/>
          <el-tab-pane :label="`草稿(${statusCount[STATUS.DRAFT]})`" :name="STATUS.DRAFT"/>
          <el-tab-pane :label="`审核中(${statusCount[STATUS.REVIEW]})`" :name="STATUS.REVIEW"/>
          <el-tab-pane :label="`未通过(${statusCount[STATUS.REJECTED]})`" :name="STATUS.REJECTED"/>
        </el-tabs>
      </div>

      <!-- 文章列表 -->
      <div class="table-container">
        <el-table
          :data="pagedArticles"
          border
          stripe
          class="articles-table"
          :empty-text="emptyText"
        >
          <!-- 状态标签列 -->
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getStatusTagType(row.type)"
                size="small"
              >
                {{ getStatusText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="文章信息" min-width="300">
            <template #default="{ row }">
              <div class="article-info">
                <div class="title">{{ row.title }}</div>
                <div class="meta-info">
                  <span class="visibility-tag">
                    {{ getVisibilityText(row.visibility) }}
                  </span>
                  <span class="update-time">发布时间: {{ row.createTime }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 移除原有的发布时间列 -->
          <el-table-column label="数据指标" width="260">
            <template #default="{ row }">
              <div class="metrics">
                <div class="metric-item">
                  <el-icon>
                    <View/>
                  </el-icon>
                  {{ row.views }} 浏览
                </div>
                <div class="metric-item">
                  <el-icon>
                    <Star/>
                  </el-icon>
                  {{ row.likeCount }} 点赞
                </div>
                <div class="metric-item">
                  <el-icon>
                    <Collection/>
                  </el-icon>
                  {{ row.collectCount }} 收藏
                </div>
                <div class="metric-item">
                  <el-icon>
                    <ChatDotRound/>
                  </el-icon>
                  {{ row.commentCount }} 评论
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="220" fixed="right">
            <template #default="{ row }">
              <el-dropdown trigger="click">
                <el-button
                  type="text"
                  class="operation-btn permission-btn"
                >
                  权限设置
                  <el-icon class="icon-arrow">
                    <ArrowDown/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      @click="changeVisibility(row, 2)"
                      :disabled="row.visibility === 2"
                    >
                      公开
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="changeVisibility(row, 1)"
                      :disabled="row.visibility === 1"
                    >
                      粉丝可见
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click="changeVisibility(row, 0)"
                      :disabled="row.visibility === 0"
                    >
                      私密
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <router-link
                :to="{ name: 'PublishPost', query: { postId: row.id} }"
                class="operation-btn edit-btn"
              >
                编辑
              </router-link>

              <el-button
                type="text"
                class="operation-btn delete-btn"
                @click="handleDelete(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="filteredArticles.length"
          :page-sizes="[8, 16, 32]"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </div>
  </div>
</template>

<!-- 脚本和样式部分保持不变 -->
<script setup>
// 原有代码保持不变
import {ref, computed} from 'vue'
import {ElMessage, ElMessageBox, ElTag} from 'element-plus'
import {deletePost, getMyPostData, updateByVisibility} from "@/api/publish.js";
import {ChatDotRound, Collection, Star, View, Search, ArrowDown} from "@element-plus/icons-vue";
import {useRouter} from 'vue-router'

const router = useRouter()

// 文章状态枚举
const STATUS = {
  ALL: 'all',
  DRAFT: 0,
  PUBLISHED: 3,
  REVIEW: 1,
  REJECTED: 2
}

// 状态文本映射
const getStatusText = (type) => {
  const statusMap = {
    [STATUS.DRAFT]: '草稿',
    [STATUS.PUBLISHED]: '已发布',
    [STATUS.REVIEW]: '审核中',
    [STATUS.REJECTED]: '未通过'
  }
  return statusMap[type] || '未知'
}

// 状态标签样式映射
const getStatusTagType = (type) => {
  const typeMap = {
    [STATUS.DRAFT]: 'info',
    [STATUS.PUBLISHED]: 'success',
    [STATUS.REVIEW]: 'warning',
    [STATUS.REJECTED]: 'danger'
  }
  return typeMap[type] || 'default'
}

// 可见性文本映射
const getVisibilityText = (visibility) => {
  const visibilityMap = {
    0: '私密',
    1: '粉丝可见',
    2: '公开'
  }
  return visibilityMap[visibility] || '未知'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 空状态文本
const emptyText = computed(() => {
  if (searchQuery.value) {
    return `没有找到包含"${searchQuery.value}"的文章`
  }
  if (activeTab.value !== STATUS.ALL) {
    return `当前${getStatusText(activeTab.value)}分类下没有文章`
  }
  return '暂无文章数据'
})

// 以下为原有代码保持不变
const posts = ref([])

const getPosts = async () => {
  const res = await getMyPostData()
  posts.value = res.data.data
}
getPosts()

const statusCount = computed(() => ({
  [STATUS.DRAFT]: posts.value.filter(p => p.type === STATUS.DRAFT).length,
  [STATUS.REVIEW]: posts.value.filter(p => p.type === STATUS.REVIEW).length,
  [STATUS.REJECTED]: posts.value.filter(p => p.type === STATUS.REJECTED).length,
  [STATUS.PUBLISHED]: posts.value.filter(p => p.type === STATUS.PUBLISHED).length
}))

const activeTab = ref(STATUS.ALL)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)

const filteredArticles = computed(() => {
  return posts.value.filter(article => {
    const matchStatus = activeTab.value === STATUS.ALL ||
      article.type === activeTab.value
    const matchSearch = article.title.includes(searchQuery.value)
    return matchStatus && matchSearch
  })
})

const pagedArticles = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredArticles.value.slice(start, start + pageSize.value)
})

const handleEdit = (id) => {
  router.push({name: 'PublishPost', query: {postId: id}})
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定永久删除该文章？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    posts.value = posts.value.filter(a => a.id !== id)
    await deletePost(id)
    ElMessage.success('删除成功')
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除失败', e)
      ElMessage.error('删除失败，请重试')
    }
  }
}

const changeVisibility = async (article, visibility) => {
  article.visibility = visibility
  try {
    await updateByVisibility(article.id, visibility)
    ElMessage.success('权限设置已更新')
  } catch (e) {
    console.error('更新权限失败', e)
    ElMessage.error('更新失败，请重试')
  }
}
</script>

<style scoped lang="scss">
// 原有样式保持不变
.article-manager {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin: 20px;

  .page-title {
    margin: 0 0 24px 0;
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    display: flex;
    align-items: center;
  }

  .control-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 16px;

    .custom-search {
      width: 300px;

      :deep(.el-input__inner) {
        height: 40px;
        border-radius: 8px;
        padding: 0 16px 0 40px;
        border-color: #e5e6eb;
        transition: all 0.3s ease;

        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }

      .search-icon {
        position: absolute;
        left: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #86909c;
        transition: color 0.3s ease;

        :deep(.el-input__inner:focus + &) {
          color: #409eff;
        }
      }
    }

    .status-tabs {
      flex-grow: 1;
      margin-left: 20px;

      :deep(.el-tabs__nav) {
        height: 40px;
      }

      :deep(.el-tabs__item) {
        padding: 0 16px;
        margin-right: 8px;
        font-size: 14px;
        color: #606266;
        transition: all 0.2s;

        &:hover {
          color: #409eff;
        }

        &.is-active {
          color: #409eff;
          font-weight: 500;
        }
      }

      :deep(.el-tabs__active-bar) {
        background-color: #409eff;
      }
    }
  }

  .table-container {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #f0f0f0;

    .articles-table {
      :deep(.el-table__header) {
        background-color: #f7f8fa;

        th {
          background-color: transparent;
          color: #4e5969;
          font-weight: 500;
          border-bottom: 1px solid #f0f0f0;
        }
      }

      :deep(.el-table__body tr:hover > td) {
        background-color: #f7f8fa;
      }

      :deep(.el-table__empty-block) {
        min-height: 200px;
        padding: 40px 0;
      }
    }
  }

  .article-info {
    padding: 4px 0;

    .title {
      font-weight: 500;
      color: #1d2129;
      margin-bottom: 6px;
      transition: color 0.2s;
      font-size: 15px;

      &:hover {
        color: #409eff;
        text-decoration: underline;
        cursor: pointer;
      }
    }

    .meta-info {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 12px;
      flex-wrap: wrap; /* 允许在小屏幕上换行 */

      .visibility-tag {
        color: #86909c;
        background-color: #f2f3f5;
        padding: 2px 8px;
        border-radius: 12px;
      }

      .update-time {
        color: #86909c;
      }
    }
  }

  .metrics {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    font-size: 13px;

    .metric-item {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #606266;

      :deep(.el-icon) {
        font-size: 14px;
        color: #86909c;
      }
    }
  }

  .operation-btn {
    padding: 0 8px;
    font-size: 14px;
    transition: all 0.2s;
    display: inline-block;
    height: 32px;
    line-height: 32px;

    &:hover {
      opacity: 0.9;
    }
  }

  .permission-btn {
    color: #606266;

    .icon-arrow {
      font-size: 12px;
      margin-left: 2px;
    }
  }

  .edit-btn {
    color: #409eff;
    text-decoration: none;
  }

  .delete-btn {
    color: #f56c6c;
  }

  .pagination {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;

    :deep(.el-pagination) {
      .el-pagination__total {
        color: #606266;
        margin-right: 12px;
      }

      .el-pager li {
        margin: 0 4px;
        border-radius: 4px;

        &.is-active {
          background-color: #409eff;
          color: #fff;
        }
      }
    }
  }
}

@media (max-width: 1024px) {
  .article-manager {
    padding: 16px;
    margin: 10px;

    .control-bar {
      flex-direction: column;
      align-items: flex-start;

      .custom-search {
        width: 100%;
      }

      .status-tabs {
        width: 100%;
        margin-left: 0;
      }
    }

    .metrics {
      gap: 8px;
    }
  }
}

@media (max-width: 768px) {
  .article-manager {
    .table-container {
      :deep(.el-table) {
        font-size: 13px;
      }
    }

    .operation-btn {
      padding: 0 6px;
      font-size: 13px;
    }

    .pagination {
      justify-content: center;

      :deep(.el-pagination) {
        flex-wrap: wrap;
      }
    }
  }
}
</style>
